package net.peelmeagrape.hibernate.ant;

import org.apache.tools.ant.BuildException;
import org.dom4j.DocumentException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import net.peelmeagrape.hibernate.config.HibernateAnnotationsProcessor;

public class GenerateMappings
{
    private File destdir;
    private List<String> classNames;
    private HibernateAnnotationsProcessor annotationsProcessor = new HibernateAnnotationsProcessor();

    public GenerateMappings(File destdir, List<String> classNames)
    {
        this.destdir = destdir;
        this.classNames = classNames;
    }

    public static void main(String[] args) throws ClassNotFoundException
    {
        File destdir = new File(args[0]);
        List<String> strings = new ArrayList<String>(Arrays.asList(args));
        strings.remove(0);
        new GenerateMappings(destdir, strings).run();
    }

    private void run() throws ClassNotFoundException
    {
        for (String className : classNames)
        {
            generateMappingFor(Class.forName(className));
        }
    }

    public void generateMappingFor(Class classToScan)
    {
        try
        {
            String mappingAsXml = annotationsProcessor.getMappingAsXml(classToScan);
            if(mappingAsXml!=null)
            {
                String mappingXmlName = classToScan.getName().replace('.','/')+".hbm.xml";
                File destFile = new File(destdir, mappingXmlName);
                destFile.getParentFile().mkdirs();
                FileWriter fileWriter = new FileWriter(destFile);
                fileWriter.write(mappingAsXml);
                fileWriter.close();
            }
        }
        catch (DocumentException e)
        {
            throw new BuildException(e.getMessage(),e);
        }
        catch (IOException e)
        {
            throw new BuildException(e.getMessage(),e);
        }
    }
}
